<?php


namespace App\Services\Sms;



use Illuminate\Support\Facades\Log;

class SmsTcby
{
    private static $api_url = 'http://jk.smstcby.com/smsUTF8.aspx';

    protected static $headers = [
        'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.2 Safari/605.1.15',
        'Content-Type' => 'text/html; charset=utf-8',
    ];

    private $params = null;


    public function __construct()
    {
        $this->getParam();
    }

    /**
     * @param null $key_name
     * @return bool|null
     */
    protected function getParam($key_name = null)
    {
        if (is_null($this->params)) {
            if (!config('user.sms_tcby')) {
                return false;
            }

            $this->params = [
//                'username' => '',
//                'password' => '',
//                'gwid' => '',
//                'mobile' => '',
//                'message' => '',
                'type' => 'send',
//                'dstime' => date('Y-m-d H:i:s', strtotime('+5 seconds')), //
                'rece' => 'json',
            ];

            $this->params = array_merge($this->params, config('user.sms_tcby'));
            isset($this->params['password']) && $this->params['password'] = strtoupper(md5($this->params['password']));
        }

        return is_null($key_name) ? $this->params : (isset($this->params[$key_name]) ? $this->params[$key_name] : false);
    }

    /**
     * @param $mobile
     * @param $code
     * @return bool|string
     */
    public function sendValidate($mobile, $code)
    {
        $message_content = "【{$this->getParam('sign')}】您的验证码为：{$code}";
        $postData = $this->getParam();

        $postData['mobile'] = $mobile;
        $postData['message'] = $message_content;

        $result = false;
        try {
            $row = parse_url(static::$api_url);
            $host = $row['host'];
            $port = isset($row['port']) ? $row['port'] : 80;
            $file = $row['path'];
            $post = "";
            foreach ($postData as $k => $v) {
                $post .= rawurlencode($k) . "=" . rawurlencode($v) . "&";
            }
            $post = substr($post, 0, -1);
            $len = strlen($post);
//            var_dump($host, $port, 10);exit;
            $fp = @fsockopen($host, $port, $errno, $errstr, 10);
            if (!$fp) {
                throw new \Exception("{$errno}: {$errstr}", 80000);
            }

            $receive = '';
            $out = "POST $file HTTP/1.1\r\n";
            $out .= "Host: $host\r\n";
            $out .= "Content-type: application/x-www-form-urlencoded\r\n";
            $out .= "Connection: Close\r\n";
            $out .= "Content-Length: $len\r\n\r\n";
            $out .= $post;
            fwrite($fp, $out);
            while (!feof($fp)) {
                $receive .= fgets($fp, 128);
            }
            fclose($fp);
            $receive = explode("\r\n\r\n", $receive);
            unset($receive[0]);

            $response_context = implode("", $receive);
            $data = json_decode($response_context, 1);
            if(json_last_error()){
                throw new \Exception('response not json formatted. ' . json_last_error_msg(), 80001);
            }

            if($data['returnstatus'] != 'success'){
                throw new \Exception("response not json formatted. code:{$data['code']}", 80001);
            }

            $result = [
                'code' => 200,
                'message' => '发送成功',
            ];
        } catch (\Exception $e) {
            Log::error("{$e->getCode()}: {$e->getMessage()}");
        }

        return $result;
    }

}